package com.example.meituan.activity.user;

import static android.app.Activity.RESULT_OK;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

import com.example.meituan.R;
import com.example.meituan.activity.bean.AdminBean;
import com.example.meituan.activity.bean.ImgBean;
import com.example.meituan.activity.bean.OrderBean;
import com.example.meituan.activity.bean.OrderDetailsBean;
import com.example.meituan.activity.bean.ShopBean;
import com.example.meituan.activity.bean.TypeBean;
import com.example.meituan.activity.bean.UserAddressBean;
import com.example.meituan.activity.user.adapter.typeAdapter;
import com.example.meituan.dao.AdminDao;
import com.example.meituan.dao.ImgDao;
import com.example.meituan.dao.TypeDao;
import com.example.meituan.dao.UserAddressDao;

import java.io.File;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

public class ShopBuy extends DialogFragment implements onItemClick {

    private ShoupBuyL listener;
    private TextView quantityTextView, price, choose, address; // 数量的 TextView
    private ShopBean shopBean;// 存储 ShopBean 实例
    private TypeBean typeBean;
    ImageView shopImg, exit, right;
    AdminBean adminBean;
    List<TypeBean> types;
    androidx.recyclerview.widget.RecyclerView recyclerView;
    int quantity;
    String detialType;
    String imagePath;
    AdminBean currentUser;
    UserAddressBean userAddressBean;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                userAddressBean = data.getParcelableExtra("userAddress");
            }
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.buy_sheet, null);

        // 初始化视图
        quantityTextView = view.findViewById(R.id.number_shop_buy);
        imagePath = "";
        shopImg = view.findViewById(R.id.shop_buy_img);
        price = view.findViewById(R.id.shop_buy_price_sheet);
        recyclerView = view.findViewById(R.id.shop_buy_type_recyclerView);
        choose = view.findViewById(R.id.shop_buy_choose);
        exit = view.findViewById(R.id.exit_shop_buy);
        address = view.findViewById(R.id.shop_buy_address);
        right = view.findViewById(R.id.shop_buy_right);
        quantity = 1;
        // 设置初始值
        if (shopBean != null) {
            createTypeButtons();
            initializeViews();
        }

        // 设置点击监听器
        setClickListeners(view);

        return builder.setView(view).create();
    }

    private void initializeViews() {
        currentUser = AdminDao.getUserInfo(getActivity());
        quantityTextView.setText(quantity + "");
        List<ImgBean> imgBeans = ImgDao.getAllImagesByShopId(shopBean.getId());
        if (imgBeans != null && !imgBeans.isEmpty()) {
            ImgBean firstImgBean = imgBeans.get(0);
            imagePath = firstImgBean.getImg();

            File imageFile = new File(imagePath);
            if (imageFile.exists()) {

                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                if (bitmap != null) {
                    shopImg.setImageBitmap(bitmap);
                }
            }
        }
        price.setText("¥" + shopBean.getPrice());
        choose.setText("已选: " + shopBean.getName() + "(" + types.get(0).getTypeDescription() + ")");
        detialType = types.get(0).getTypeDescription();
        if (userAddressBean != null) {
            address.setText(userAddressBean.getS_address());
        } else {
            List<UserAddressBean> addressBeanList = UserAddressDao.getUserAddressesByUserId(currentUser.getUserId());
            if (addressBeanList != null && addressBeanList.size() != 0) {
                address.setText(addressBeanList.get(0).getS_address());
            } else {
                address.setText("-");
            }
        }
    }

    private void createTypeButtons() {
        types = TypeDao.getAllTypesByShopId(shopBean.getId()); // 获取所有类型
        if (types == null || types.isEmpty()) {
            Toast.makeText(getContext(), "没有数据显示", Toast.LENGTH_SHORT).show();
            recyclerView.setAdapter(null);
        } else {
            typeAdapter adapter = new typeAdapter(types, ShopBuy.this);
            recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 5));
            recyclerView.setAdapter(adapter);
        }

    }


    private void setClickListeners(View view) {
        // 找到加减按钮并设置监听器
        view.findViewById(R.id.minus_shop_buy).setOnClickListener(v -> {
            if (quantity > 1) { // 使用 ShopBean 中的最小数量
                quantity--;
                updateQuantityView();
            }
        });

        view.findViewById(R.id.buy_shop_add).setOnClickListener(v -> {
            quantity++;
            updateQuantityView();
        });

        view.findViewById(R.id.buy_sheet).setOnClickListener(v -> {
            String id = UUID.randomUUID().toString().replace("-", "");
            OrderBean orderBean = new OrderBean();
            orderBean.setsId(id);
            adminBean = AdminDao.getUserInfo(v.getContext());
            orderBean.setsUserId(adminBean.getUserId());
            orderBean.setsBusinessId(shopBean.getBusinessId());
            String addressText = address.getText().toString();
            orderBean.setsOrderAddress(addressText);
            orderBean.setsOrderSta("未发货");
            long timestamp = System.currentTimeMillis();
            String formattedDate = Instant.ofEpochMilli(timestamp)
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime()
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            orderBean.setsOrderTime(formattedDate);
            String detialsId = UUID.randomUUID().toString().replace("-", "");
            orderBean.setsOrderDetialsId(detialsId);
            OrderDetailsBean orderDetailsBean = new OrderDetailsBean();
            orderDetailsBean.setShopId(shopBean.getId());
            orderDetailsBean.setDetailType(detialType);
            orderDetailsBean.setId(detialsId);
            orderDetailsBean.setName(shopBean.getName());
            orderDetailsBean.setPrice(shopBean.getPrice());
            orderDetailsBean.setDescription(shopBean.getDes());
            orderDetailsBean.setNum("" + quantity);
            orderDetailsBean.setImg(imagePath);
        });

        view.findViewById(R.id.exit_shop_buy).setOnClickListener(v -> {
            if (listener != null) {
                listener.exit();
            }
        });
        view.findViewById(R.id.shop_buy_right).setOnClickListener(v -> {
            if (listener != null) {
                listener.toAddress();
            }
        });
    }

    private void updateQuantityView() {
        quantityTextView.setText(String.valueOf(quantity));
    }

    public void show(ShoupBuyL listener, ShopBean shopBean, androidx.fragment.app.FragmentManager fragmentManager) {
        this.listener = listener;
        this.shopBean = shopBean;
        super.show(fragmentManager, "product_details");
    }

    @Override
    public void onItemClick(TypeBean type) {
        typeBean = type;
        choose.setText("已选: " + shopBean.getName() + "(" + type.getTypeDescription() + ")");
        detialType = type.getTypeDescription();
    }

    public interface ShoupBuyL {
        void exit();

        void toAddress();
    }

}
